﻿using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Choucius.Boilerplate9.MesApiClients
{
    public class MesApiClient : IMesApiClient
    {
        private readonly IHttpClientFactory _httpClientFactory;

        public MesApiClient(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        public async Task<string> GetAsync(string url)
        {
            using (var httpClient = _httpClientFactory.CreateClient())
            {
                return await httpClient.GetStringAsync(url);
            }
        }

        public async Task<string> PostAsync(string url, object data)
        {
            using (var httpClient = _httpClientFactory.CreateClient())
            {
                var content = new StringContent(JsonSerializer.Serialize(data), Encoding.UTF8, "application/json");
                var response = await httpClient.PostAsync(url, content);
                response.EnsureSuccessStatusCode();
                return await response.Content.ReadAsStringAsync();
            }
        }
    }
}
